package com.yanghui.dtracing.log4j2;

import com.yanghui.dtracing.core.opentracing.DTracerSpan;
import com.yanghui.dtracing.core.opentracing.reporter.Reporter;
import org.apache.logging.log4j.ThreadContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Log4j2Reporter implements Reporter {

    private final Logger log = LoggerFactory.getLogger(Log4j2Reporter.class);

    @Override
    public void init() {
    }

    @Override
    public void report(DTracerSpan span) {
        try{
            ThreadContext.put("spanId",span.context().toSpanId());
            ThreadContext.put("parentId",span.context().getParentId());
            ThreadContext.put("msName",span.getServiceName());
            ThreadContext.put("traceId",span.context().toTraceId());
            ThreadContext.put("className",span.getClassName());
            ThreadContext.put("method",span.getOperationName());
            ThreadContext.put("costTime",String.valueOf(span.getCostTime()));
            ThreadContext.put("startTime", DateUtil.toDateStr(span.getStartTime()));
            ThreadContext.put("endTime", DateUtil.toDateStr(span.getEndTime()));
            ThreadContext.put("asyn",span.context().getBaggageItems().get("asyn"));
            log.info("trace log");
        }finally {
            ThreadContext.clearAll();
        }
    }

    @Override
    public void close() {
    }
}
